<template>
    <span class="copy-container">
        <slot v-if="slots.default" :label="label" :status="status" :copy="handleCopy" />
        <template v-else>
            {{ label }}
        </template>

        <!-- 动态图标组件 -->
        <component :is="iconList[status].component" v-bind="iconList[status].attrs"
            :class="['copy-icon', iconList[status].className]" />
    </span>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, useSlots } from 'vue'
import { Check, Close, CopyDocument } from '@element-plus/icons-vue';

const props = defineProps({
    value: [String, Number],
    label: [String, Number]
})

const status = ref('none')
const timer = ref(null)
const slots = useSlots()

// 兼容现代和传统浏览器的复制方法 
const copyToClipboard = async (text) => {
    try {
        if (navigator.clipboard) {
            await navigator.clipboard.writeText(text)
            return true
        } else {
            const textarea = document.createElement('textarea')
            textarea.value = text
            textarea.style.position = 'fixed'
            document.body.appendChild(textarea)
            textarea.select()
            const success = document.execCommand('copy')
            document.body.removeChild(textarea)
            return success
        }
    } catch (err) {
        console.error('复制失败:', err)
        return false
    }
}

const handleCopy = async () => {
    if (props.value || props.label) {
        const isSuccess = await copyToClipboard(props.value || props.label)
        status.value = isSuccess ? 'success' : 'error'
        timer.value = setTimeout(() => (status.value = 'none'), 1500)
    }
}

// 状态图标映射 (网页6最佳实践)
const iconList = computed(() => ({
    success: {
        component: Check,
        className: 'success-icon'
    },
    error: {
        component: Close,
        className: 'error-icon'
    },
    none: {
        component: CopyDocument,
        className: 'copy-icon',
        attrs: {
            onClick: handleCopy,
            title: '复制'
        }
    }
}))

// 自动清除定时器 (网页4生命周期处理)
onBeforeUnmount(() => {
    if (timer.value) clearTimeout(timer.value)
})
</script>



<style scoped>
.copy-container {
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.copy-icon {
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
        color: #1890ff;
    }

    &.success-icon {
        color: #24b588;
    }

    &.error-icon {
        color: #f44336;
    }
}
</style>